import type Store from 'electron-store'
import type { AppSetting } from '../entity/appSetting.js'
import type { DBConfig } from './index.js'
import { getDB } from './dbFactory.js'

const SAVE_KEY = 'appSetting'
const PRI_KEY = 'appKey'

export interface AppSettingDB extends DBConfig {
  addAppSetting: (value: AppSetting) => boolean
  updateAppSetting: (val: AppSetting) => void
  deleteAppSetting: (id: number) => void
  getAppSetting: (id: string) => AppSetting
  setAppSetting: (appSetting: AppSetting) => void
  tableName: string
  tableVersion: number
}

function useDB(db: Store): AppSettingDB {
  return {
    tableName: 'app_setting',
    tableVersion: 1.0,
    initTable() {
      // db.exec('create table IF NOT EXISTS app_setting(id integer not nullconstraint test_pk primary key autoincrement,nickName TEXT,path TEXT,projectName TEXT,sortType TEXT);');
    },
    addAppSetting(appSetting: AppSetting) {
      this.setAppSetting(appSetting)
      db.set('appKey', appSetting.id)
      return true
      // const stmt = db.prepare('INSERT INTO app_setting (id, nickName,path,projectName,sortType) VALUES (?, ?)');
      // return stmt.run(appSetting.id, appSetting.nikeName, appSetting.path, appSetting.projectName);
    },
    updateAppSetting(appSetting: AppSetting) {
      this.setAppSetting(appSetting)
      this.setAppSetting(PRI_KEY, appSetting.id)
      // const stmt = db.prepare("update set app_setting value(id,) key, value FROM app_setting where key = :key");
      // return stmt.run(appSetting.id, appSetting.nikeName, appSetting.path, appSetting.projectName);
    },
    deleteAppSetting(id: number) {
      if (id == db.get(PRI_KEY)) {
        db.delete(SAVE_KEY)
      }

      // const stmt =db.prepare('delete from app_setting where id = ?');
      // return stmt.run(id);
    },
    getAppSetting(key: string = 'app'): AppSetting {
      console.log('get app_set', key)
      console.log(SAVE_KEY, db.get(SAVE_KEY))
      console.log(PRI_KEY, db.get(PRI_KEY))
      return db.get(SAVE_KEY) as AppSetting
      // const stmt = db.prepare("SELECT key, value FROM app_setting where id = ?");
      // return stmt.get(key) as AppSetting;
    },
    setAppSetting(appSetting: AppSetting) {
      db.set(SAVE_KEY, appSetting)
    },
  }
}

const appSettingDB = useDB(getDB())
export default appSettingDB
